﻿using System.Collections.Generic;

namespace Shape.Events
{
	public class EventAggregator : IEventAggregator
	{
	#region Fields
		private IList<ISubscriber> _subscribers = new List<ISubscriber>();
	#endregion

	#region Public Interface
		public void Subscribe(ISubscriber subscriber)
		{
			_subscribers.Add(subscriber);
		}

		public void Publish<TEvent>(TEvent item)
		{
			// Iterate using index to cater for situation where published event may
			// add additional subscribers
			for (int i = 0; i <= _subscribers.Count - 1; i++)
			{
				var subscriber = _subscribers[i] as ISubscriber<TEvent>;

				if (subscriber != null) 
				{
					subscriber.Handle(item);
				}   
					
			};
		}
	#endregion

	}
}
